package zcw.com.lib_leet_code;

import java.util.Arrays;
import java.util.List;

import zcw.com.lib_leet_code.bean.TreeNode;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/7/8.<br><br>
 *
 * 路径总和
 */
public class Topic112 {
    public static void main(String[] args) {
        Topic112 instance = new Topic112();

        List<Integer> list = Arrays.asList(5,4,8,11,null,13,4,7,2,null,null,null,1);
        TreeNode root = Util.createTree(list);
        System.out.println(instance.hasPathSum(root, 22));

        list = Arrays.asList(1,2,3);
        root = Util.createTree(list);
        System.out.println(instance.hasPathSum(root, 5));

        list = Arrays.asList(1,2);
        root = Util.createTree(list);
        System.out.println(instance.hasPathSum(root, 0));

        System.out.println(instance.hasPathSum(root, 1));
    }

    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null) {
            return false;
        }

        if(root.val == targetSum && root.left == null && root.right == null) {
            return true;
        }

        return hasPathSum(root.left, targetSum - root.val) ||
                hasPathSum(root.right, targetSum - root.val);
    }
}
